package com.llt.controller;

import com.llt.annotation.UserLoginToken;
import com.llt.enum_util.ResponseBodyEnum;
import com.llt.pojo.UserInfo;
import com.llt.pojo.common.AjaxResponseBody;
import com.llt.service.UserInfoService;
import com.llt.utils.Utils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
@RestController
@CrossOrigin
@Api(value = "登录后台",tags = {"登录后台"})
public class Login {
    @Autowired
    private UserInfoService userInfoService;

    @GetMapping("/isLogin")
    @ResponseBody
    @UserLoginToken
    @ApiOperation(value = "是否登录",response = AjaxResponseBody.class)
    public AjaxResponseBody isLogin(){

        return  new AjaxResponseBody(ResponseBodyEnum.RESPONSE_BODY_ENUM_OK);
    }

    @PostMapping("/login")
    @ResponseBody
    @ApiOperation(value = "用户登录",response = UserInfo.class)
    public AjaxResponseBody login(
            @Validated @RequestBody  UserInfo userInfo,
            HttpServletResponse httpServletResponse){
        UserInfo data = userInfoService.userQueryByName(userInfo.getUsername());
        if (data==null){
            //用户不存在
            return  new AjaxResponseBody(ResponseBodyEnum.RESPONSE_BODY_USER_NOT_FIND);
        }
        String  data2 = userInfo.getPassword();
        if (!data.getPassword().equals(data2)){
            //密码不正确
            return  new AjaxResponseBody(ResponseBodyEnum.RESPONSE_BODY_USER_LOGIN_ERROR);
        }
        long time  =7* 60 * 60 * 1000;//7小时
        String token = Utils.getToken(userInfo.getUsername(),time);

        //成功
        Cookie cookie = new Cookie("token",token);
        httpServletResponse.addCookie(cookie);
        return  new AjaxResponseBody(ResponseBodyEnum.RESPONSE_BODY_ENUM_OK,userInfo,token);
    }
}
